package com.mc.clt.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mc.clt.domain.*;
import com.mc.clt.mapper.*;
import com.mc.clt.service.ICltService;
import com.mc.clt.task.CltExpireTask;
import com.mc.common.constant.Constants;
import com.mc.common.core.domain.entity.SysUser;
import com.mc.common.core.domain.model.LoginUser;
import com.mc.common.utils.DateUtils;
import com.mc.common.utils.ServletUtils;
import com.mc.framework.web.service.TokenService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class CltServiceImpl implements ICltService {
    @Autowired
    private CltResultGermplasmMapper  germplasmMapper;
    @Autowired
    private CltResultSpecimenMapper specimenMapper;
    @Autowired
    private CltResultMapper resultMapper;
    @Autowired
    private CltMultimediaMapper multimedia;
    @Autowired
    private LabMapper labAuthenticateMapper;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private CltResultUserMapper cltResultUserMapper;

    private static final org.slf4j.Logger log = LoggerFactory.getLogger(CltServiceImpl.class);

    @Override
    public List<CltResultGermplasm> selectGermplasmByName(CltInfo cltInfo) {
        List<CltResultGermplasm> returnList = new ArrayList<CltResultGermplasm>();
        List<CltResultGermplasm> list = germplasmMapper.selectCltResultGermplasmList(cltInfo);
        for(CltResultGermplasm ger : list){
            CltMultimedia cltMultimedia = new CltMultimedia();
            cltMultimedia.setCltId(ger.getCltResultId());
            Lab labAuthenticate = new Lab();
            labAuthenticate.setCltId(ger.getCltResultId());
            ger.setPhotoPath(JSONArray.toJSON( labAuthenticateMapper.selectLabAuthenticateList(labAuthenticate)).toString());
            ger.setAuthenticateNameList(JSONArray.toJSON( multimedia.selectCltMultimediaList(cltMultimedia)).toString());
            returnList.add(ger);
        }
        return returnList;
    }

    @Override
    public List<CltResultSpecimen> selectSpecimenByName(CltInfo cltInfo) {
        List<CltResultSpecimen> returnList = new ArrayList<CltResultSpecimen>();
        List<CltResultSpecimen> list =  specimenMapper.selectCltResultSpecimenList(cltInfo);
        for(CltResultSpecimen spe : list){
            CltMultimedia cltMultimedia = new CltMultimedia();
            cltMultimedia.setCltId(spe.getCltResultId());
            Lab labAuthenticate = new Lab();
            labAuthenticate.setCltId(spe.getCltResultId());
            spe.setPhotoPath(JSONArray.toJSON( labAuthenticateMapper.selectLabAuthenticateList(labAuthenticate)).toString());
            spe.setAuthenticateNameList(JSONArray.toJSON( multimedia.selectCltMultimediaList(cltMultimedia)).toString());
            returnList.add(spe);
        }
        return returnList;
    }

    @Override
    public List<CltResult> selectCltByDate(String date) {
        List<CltResult> returnList = new ArrayList<CltResult>();
        List<CltResult> list = resultMapper.selectCltResultListByLastDate(date);
        for(CltResult result : list){
            CltMultimedia cltMultimedia = new CltMultimedia();
            cltMultimedia.setCltId(result.getResultId());
            Lab labAuthenticate = new Lab();
            labAuthenticate.setCltId(result.getResultId());
            result.setAuthenticateNameList(JSONArray.toJSON( labAuthenticateMapper.selectLabAuthenticateList(labAuthenticate)).toString());
            result.setImagePath(multimedia.selectCltMultimediaList(cltMultimedia));
            returnList.add(result);
        }
        return returnList;
    }

    @Override
    public List<CltResult> selectCltAll(String num) {
        List<CltResult> returnList = new ArrayList<CltResult>();
        List<CltResult> list = resultMapper.selectRealTimeCltResultList(num);
        for(CltResult result : list){
            CltMultimedia cltMultimedia = new CltMultimedia();
            cltMultimedia.setCltId(result.getResultId());
            Lab labAuthenticate = new Lab();
            labAuthenticate.setCltId(result.getResultId());
            CltResultUser cltResultUser = new CltResultUser();
            cltResultUser.setCltId(result.getResultId());
            result.setAuthenticateNameList(JSONArray.toJSON( labAuthenticateMapper.selectLabAuthenticateList(labAuthenticate)).toString());
            result.setImagePath(multimedia.selectCltMultimediaList(cltMultimedia));
            returnList.add(result);
        }
        return returnList;
    }
    @Transactional //多次插入开启事务
    @Override
    public void insertCltResultGermplasm(CltResultGermplasm germplasm) {
        String uuid1  = UUID.randomUUID().toString().replaceAll("-","");
        String uuid2  = UUID.randomUUID().toString().replaceAll("-","");
        germplasm.setResultId(uuid1);
        germplasm.setCltResultId(uuid1);
        germplasm.setId(uuid2);
        germplasm.setIsAuthenticate("0");
        // 图片
        List<CltMultimedia> multimediaList = germplasm.getImagePath();
        List<CltResultUser> cltResultUsers = germplasm.getUsers();
        for(CltResultUser cltResultUser : cltResultUsers){
            cltResultUser.setCltId(uuid1);
            cltResultUserMapper.insertCltResultUserResult(cltResultUser);
        }
        resultMapper.insertCltResult(germplasm);
        germplasmMapper.insertCltResultGermplasm(germplasm);
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        for(CltMultimedia cltMultimedia : multimediaList){
            cltMultimedia.setCltId(uuid1);
            cltMultimedia.setCreatedTime(DateUtils.getNowDate());
            cltMultimedia.setCreatedBy(loginUser.getUsername());
            SysUser user = loginUser.getUser();
            multimedia.insertCltMultimedia(cltMultimedia);
        }
        try{
            germplasm.setObjectId(restTemplate(germplasm,"addFeatures"));
            resultMapper.updateCltResult(germplasm);
        }catch (Exception e){

        }finally {

        }

    }
    @Transactional//多次插入开启事务
    @Override
    public void insertCltResultSpecimen(CltResultSpecimen specimen) {
        String uuid1  = UUID.randomUUID().toString().replaceAll("-","");
        String uuid2  = UUID.randomUUID().toString().replaceAll("-","");
        specimen.setResultId(uuid1);
        specimen.setCltResultId(uuid1);
        specimen.setId(uuid2);
        specimen.setIsAuthenticate("0");
        List<CltMultimedia> multimediaList = specimen.getImagePath();
        List<CltResultUser> cltResultUsers = specimen.getUsers();
        for(CltResultUser cltResultUser : cltResultUsers){
            cltResultUser.setCltId(uuid1);
            cltResultUserMapper.insertCltResultUserResult(cltResultUser);
        }
        resultMapper.insertCltResult(specimen);
        specimenMapper.insertCltResultSpecimen(specimen);
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        for(CltMultimedia cltMultimedia : multimediaList){
            cltMultimedia.setCltId(uuid1);
            cltMultimedia.setCreatedTime(DateUtils.getNowDate());
            cltMultimedia.setCreatedBy(loginUser.getUsername());
            multimedia.insertCltMultimedia(cltMultimedia);
        }
        try{
            specimen.setObjectId(restTemplate(specimen,"addFeatures"));
            resultMapper.updateCltResult(specimen);
        }catch (Exception e){

        }finally {

        }
    }

    @Override
    public CltResult selectCltResult(String id) {
        return resultMapper.selectCltResultById(id);
    }

    @Override
    public List<CltResult> selectCltResultByTaskId(String taskId) {
        return resultMapper.selectCltResultByTaskId(taskId);
    }

    @Override
    public List<CltResultGermplasm> selectGermplasmByCltID(String id) {
        List<CltResultGermplasm> returnList = new ArrayList<CltResultGermplasm>();
        List<CltResultGermplasm> list = germplasmMapper.selectCltResultGermplasmById(id);
        for(CltResultGermplasm ger : list){
            CltMultimedia cltMultimedia = new CltMultimedia();
            cltMultimedia.setCltId(ger.getCltResultId());
            Lab labAuthenticate = new Lab();
            labAuthenticate.setCltId(ger.getCltResultId());
            ger.setImagePath(multimedia.selectCltMultimediaList(cltMultimedia));
            ger.setAuthenticateNameList(JSONArray.toJSON( labAuthenticateMapper.selectLabAuthenticateList(labAuthenticate)).toString());
            returnList.add(ger);
        }
        return returnList;
    }

    @Override
    public List<CltResultSpecimen> selectSpecimenByCltID(String id) {
        List<CltResultSpecimen> returnList = new ArrayList<CltResultSpecimen>();
        List<CltResultSpecimen> list =  specimenMapper.selectCltResultSpecimenById(id);
        for(CltResultSpecimen spe : list){
            CltMultimedia cltMultimedia = new CltMultimedia();
            cltMultimedia.setCltId(spe.getCltResultId());
            Lab labAuthenticate = new Lab();
            labAuthenticate.setCltId(spe.getCltResultId());
            spe.setImagePath(multimedia.selectCltMultimediaList(cltMultimedia));
            spe.setAuthenticateNameList(JSONArray.toJSON( labAuthenticateMapper.selectLabAuthenticateList(labAuthenticate)).toString());
            returnList.add(spe);
        }
        return returnList;
    }

    @Override
    public List<CltResult> selectCltResultListByCltInfo(CltInfo cltInfo) {
        return resultMapper.selectCltResultListByCltInfo(cltInfo);
    }

    @Override
    public int countCltResult(String type) {
        return resultMapper.countCltResult(type);
    }

    @Override
    public List<CltResult> selectCltResultList(CltResult cltResult) {
        return resultMapper.selectCltResultList(cltResult);
    }

    @Override
    public List<CltResultSpecimen> selectCltResultSpecimenByTaskId(String taskId) {
        return specimenMapper.selectCltResultSpecimenByTaskId(taskId);
    }

    @Override
    public List<CltResultGermplasm> selectCltResultGermplasmByTaskIdList(String taskId) {
        return germplasmMapper.selectCltResultGermplasmByTaskIdList(taskId);
    }

    @Override
    public int countAllCltResult(CltInfo cltInfo) {
        return resultMapper.countAllCltResult(cltInfo);
    }

    @Override
    public int countCltFamily() {
        return resultMapper.countCltFamily();
    }

    @Override
    public List<CltRank> countCltRank(String name) {
        return resultMapper.countCltRank(name);
    }

    @Override
    public List<CltSpecies> countCltSpecies(String name) {
        return resultMapper.countCltSpecies(name);
    }

    @Override
    public int countAllCltSpecimenResult(CltInfo cltInfo) {
        return resultMapper.countAllCltSpecimenResult(cltInfo);
    }

    public String restTemplate(CltResult cltResult,String action){
        RestTemplate restTemplate = new RestTemplate();
        log.info("================ start =====================");
        MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
        params.add("f","pjson");
        params.add("frollbackOnFailure", "true");
        String cltTime = null;
        if(cltResult.getCollectionTime() !=null && !"".equals(cltResult.getCollectionTime())){
            cltTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:dd").format(cltResult.getCollectionTime());
        }
        params.add("features", "[{\"attributes\": {\n" +
                "    \"NAME\": \"\",\n" +
                "    \"TOPOGRAPHY\": \""+cltResult.getTopography()+"\",\n" +
                "    \"SLOPE_DEGREE\": \""+cltResult.getSlopeDegree()+"\",\n" +
                "    \"SLOPE_ASPECT\": \""+cltResult.getSlopeAcpect()+"\",\n" +
                "    \"SLOPE_POSITION\": \""+cltResult.getSlopePosition()+"\",\n" +
                "    \"CLT_TIME\": \""+cltTime+"\",\n" +
                "    \"TOPOGRAPHY\": \""+cltResult.getTopography()+"\",\n" +
                "    \"LOCATION\": \""+cltResult.getLocation()+"\",\n" +
                "    \"COUNTY\": \""+cltResult.getAreaCode()+"\",\n" +
                "   },\n" +
                "   \"geometry\": {\n" +
                "    \"x\": "+cltResult.getLongitude()+",\n" +
                "    \"y\": "+cltResult.getLatitude()+"\n" +
                "   }}]");
        log.info("params:"+params.toString());
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, null);
        ResponseEntity<String> response = restTemplate.postForEntity(
                Constants.GIS_SERVER_URL+action,
                requestEntity,
                String .class);
        String jsonObject = response.getBody();
        if(action.equals("addFeatures")){
            return JSONObject.parseObject(jsonObject).getJSONArray("addResults").getJSONObject(0).getString("objectId");
        }else if(action.equals("updateFeatures")){
            return JSONObject.parseObject(jsonObject).getJSONArray("updateResults").getJSONObject(0).getString("objectId");
        }else{
            return null;
        }

    }

}
